#
# author:Maker Sun
# http://suniot.top
# 2024.9

import json
import os
import time
from micropython import const

options_file_name = const('options.json')

class FeedSetting():
    #喂食设置
    def __init__(self, t, s):
        self.time = t
        self.set = s
    
class Options():
    #系统配置
    def __init__(self):
        self.device_key = None #设备的key
        self.ssid = None
        self.pwd = None
        self.feed_settings = None
        self.feed_setting_msg_id = None #喂食设置的id
        self.feeding_msg_id = None #上次喂食消息的id
        
    def load(self):
        if options_file_name in os.listdir():
            print('发现配置文件')
            with open(options_file_name, 'r') as f:
                data = json.load(f)
                self.device_key = data.get('key')
                self.ssid = data.get('ssid')
                self.pwd = data.get('pwd')
                self.feed_setting_msg_id = data.get('feed_setting_msg_id')
                self.feeding_msg_id = data.get('feeding_msg_id')
                self.feed_settings = []
                self.load_feed_settings(data.get('feedsettings'))
                print('load ok, feedsettings are:', self.feed_setting_msg_id, self.feed_settings)
    def save(self):
        data = {'key':self.device_key,
                'ssid': self.ssid,
                'pwd': self.pwd,
                'feed_setting_msg_id': self.feed_setting_msg_id,
                'feeding_msg_id': self.feeding_msg_id,
                'feedsettings':[{'time': s.time, 'set': s.set} for s in self.feed_settings]}
        with open(options_file_name, 'w') as f:
            json.dump(data, f)
        print('写入配置文件成功...')
    
    def load_feed_settings(self, data):
        if data and len(data)>0:
            self.feed_settings = [FeedSetting(d.get('time'), d.get('set')) for d in data] #读取热点配置信息，返回(ssid, pwd)
            self.feed_settings.sort(key=lambda x: x.time)
        else:
            self.feed_settings = []
        
    
    def get_next_feed_time(self)->FeedSetting:
        #根据系统配置获取下一次的喂食设置
        if len(self.feed_settings)==0:
            return None
        t = time.localtime()
        ts = f"{t[3]:0>{2}}:{t[4]:0>{2}}"
        for s in self.feed_settings:
            if s.time>ts:
                return s
        #都比当前时间小，从头开始设置
        return self.feed_settings[0]